<script setup>
import { RouterLink, RouterView, useRoute, useRouter } from "vue-router";
import { ref, watch, nextTick } from "vue";

const route = useRoute();
const router = useRouter();
const transitionName = ref("slide-left");
let routeHistory = [];

// 初始化路由历史
routeHistory.push(route.path);

// 监听路由变化，决定动画方向
watch(
  () => route.path,
  (newPath, oldPath) => {
    const currentIndex = routeHistory.indexOf(newPath);
    const lastIndex = routeHistory.indexOf(oldPath);

    if (currentIndex === -1) {
      // 新路由，添加到历史
      routeHistory.push(newPath);
      transitionName.value = "slide-left"; // 前进：左出右进
    } else if (currentIndex < lastIndex) {
      // 后退到之前的路由
      transitionName.value = "slide-right"; // 后退：右出左进
    } else {
      // 可能是前进或其他情况
      transitionName.value = "slide-left";
    }

    // 限制历史记录长度
    if (routeHistory.length > 10) {
      routeHistory = routeHistory.slice(-10);
    }
  }
);
</script>

<template>
  <div class="router-container">
    <transition :name="transitionName" mode="out">
      <RouterView :key="route.path" />
    </transition>
  </div>
</template>

<style scoped>
.router-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background: linear-gradient(135deg, #4f008c 0%, #7d07e4 100%);
}

/* 前进动画：左出右进 */
.slide-left-enter-active,
.slide-left-leave-active {
  transition: all 0.3s cubic-bezier(0.55, 0, 0.1, 1);
  position: absolute;
  width: 100%;
  height: 100%;
}

.slide-left-enter-from {
  transform: translateX(100%);
  opacity: 0;
}

.slide-left-enter-to {
  transform: translateX(0);
  opacity: 1;
}

.slide-left-leave-from {
  transform: translateX(0);
  opacity: 1;
}

.slide-left-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}

/* 后退动画：右出左进 */
.slide-right-enter-active,
.slide-right-leave-active {
  transition: all 0.3s cubic-bezier(0.55, 0, 0.1, 1);
  position: absolute;
  width: 100%;
  height: 100%;
}

.slide-right-enter-from {
  transform: translateX(-100%);
  opacity: 0;
}

.slide-right-enter-to {
  transform: translateX(0);
  opacity: 1;
}

.slide-right-leave-from {
  transform: translateX(0);
  opacity: 1;
}

.slide-right-leave-to {
  transform: translateX(100%);
  opacity: 0;
}
</style>
